<template>
  <cl-page>
    <view class="page">
      <!-- 收货地址 -->
      <address-select :data="info?.address" disabled />
      <!-- 商品列表 -->
      <goods-group :data="info?.goodsList" readonly />

      <view class="card">
        <text class="label">价格明细</text>

        <cl-list-item :label="`商品总价（共${info?.goodsList?.length || 0}件商品）`" :arrow-icon="false">
          <template #icon>
            <cl-icon class-name="shop-icon-q-order" :size="40"></cl-icon>
          </template>

          <cl-text :size="28" type="price" :value="info?.price" />
        </cl-list-item>

        <!--cl-list-item label="优惠券">
					<template #icon>
						<cl-icon class-name="shop-icon-coupon" :size="40"></cl-icon>
					</template>

					<coupon-select :total-amount="totalAmount" :ref="setRefs('couponSelect')" />
				</cl-list-item-->

        <cl-list-item label="运费" :arrow-icon="false">
          <template #icon>
            <cl-icon class-name="shop-icon-order-received" :size="40"></cl-icon>
          </template>

          <cl-text :size="28" type="price" :value="info?.freightPrice"></cl-text>
        </cl-list-item>

        <cl-list-item label="合计" :arrow-icon="false">
          <template #icon>
            <cl-icon class-name="shop-icon-q-pay" :size="40"></cl-icon>
          </template>

          <cl-text :size="32" type="price" line-through :value="totalAmount"></cl-text>
          <cl-text :size="32" type="price" :value="info?.payPrice"></cl-text>
        </cl-list-item>
      </view>

      <view class="card">
        <text class="label">支付方式</text>

        <cl-radio-group fill v-model="form.payType">
          <cl-radio v-for="item in order.payTypes" :key="item.key" :label="item.key" :height="80">
            {{ item.label }}
            <image class="pay-icon" mode="aspectFill" :src="item.icon" />
          </cl-radio>
        </cl-radio-group>
      </view>
    </view>

    <cl-footer :flex="false" border :padding="24">
      <cl-row type="flex" justify="space-between">
        <cl-text type="price" color="error" :size="50" :value="info?.payPrice" />
        <cl-button type="primary" :width="200" :loading="loading" @tap="submit">支付订单</cl-button>
      </cl-row>
    </cl-footer>
  </cl-page>
</template>

<script lang="ts" setup>
  import { onPullDownRefresh, onReady, onShow } from "@dcloudio/uni-app";
  import { useCool, useStore } from "/@/cool";
  import { computed, reactive, ref } from "vue";
  import { useAddress, useShoppingCart } from "/@/hooks";
  import { useUi } from "/$/cool-ui";
  import AddressSelect from "/@/components/address/select.vue";
  import CouponSelect from "/@/components/coupon/select.vue";
  import GoodsGroup from "/@/components/goods/group.vue";
  import { useOrder } from "/@/hooks";

  const { router, service, refs, setRefs } = useCool();
  const { user } = useStore();
  const address = useAddress();
  const ui = useUi();
  const spCart = useShoppingCart();
  const order = useOrder();

  // 表单
  const form = reactive({
    payType: "wxpay" as "wxpay" | "alipay",
    remark: "",
  });

  // 提交中
  const loading = ref(false);

  // 订单详情
  const info = ref<OrderInfo>();

  // 总金额
  const totalAmount = computed(() => {
    return (parseFloat(info.value?.price) + parseFloat(info.value?.freightPrice)).toFixed(2)
  });

  // 获取订单信息
  const queryOrder = async () => {
    const orderId = router.query.id;
    let order;

    ui.showLoading();
    await service.order.info
      .info({
        id: orderId,
      })
      .then((res) => {
        info.value = res;
        order = res;
      })
      .catch((err) => {
        ui.showTips(err.message, () => {
          router.back();
        });
      });

    ui.hideLoading();

    // 校验订单信息
    if (order?.userId && order?.userId != user.info.id) {
      ui.showTips("您无权访问该订单");
      return;
    }
    if (order?.status == 7) {
      ui.showTips("该订单已失效");
      return;
    }
    if (order?.status != 0) {
      ui.showTips("该订单已支付", () => {
        nextToDetail(orderId);
      })
    }
  }

  // 提交
  async function submit() {
    loading.value = true;
    // 订单id
    const orderId = info.value?.id;

    await service.order.info
      .bind({
        orderId,
      })
      .then(async (res) => {
        await order
          .toPay(orderId)
          .then(() => {
            nextToDetail(orderId);
          })
          .catch((err) => {
            ui.showTips(err.message, () => {
              nextToDetail(orderId);
            });
          });
      })
      .catch((err) => {
        ui.showTips(err.message);
      });

    loading.value = false;
  }

  // 跳转订单详情
  const nextToDetail = (id) => {
    router.push({
      path: "/pages/order/detail",
      query: {
        id,
      },
      mode: "redirectTo",
    });
  }

  onPullDownRefresh(async () => {
    await queryOrder();
    uni.stopPullDownRefresh();
  });

  onReady(() => {
    queryOrder();
  });

  onShow(() => {
    if (ui.loaded) {
      queryOrder();
    }
  });
</script>

<style lang="scss" scoped>
  .page {
    padding: 24rpx;

    .pay-icon {
      height: 56rpx;
      width: 56rpx;
      position: absolute;
      right: 0;
      top: calc(50% - 28rpx);
    }
  }
</style>